﻿/******************************************************************************
 *  All Rights Reserved , Copyright (C) 2012 , EricHu. 
 *  作    者： EricHu
 *  创建时间： 2012-3-30 13:00:39
 ******************************************************************************/

using System;
using System.Collections.Generic;
using System.Data;

namespace RDIFramework.ServiceAdapter
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.Utilities;

     /// <summary>
     /// PiOrganizeManager
     /// 组织机构、部门
     ///
     /// 修改纪录
     ///
     ///        2013-05-12 版本：2.5 EricHu 修改客户提出的“Enabled”字段异常问题。
     ///		2012-03-02 版本：1.0 EricHu 创建主键。
     ///
     /// 版本：1.0
     ///
     /// <author>
     ///		<name>EricHu</name>
     ///		<date>2012-03-02</date>
     /// </author>
     /// </summary>
    public partial class PiOrganizeManager : DbCommonManager, IDbCommonManager
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public PiOrganizeManager()
        {
            base.CurrentTableName = PiOrganizeTable.TableName;
            base.PrimaryKey = "Id";
        }

        /// <summary>
        /// 构造函数
        /// <param name="tableName">指定表名</param>
        /// </summary>
        public PiOrganizeManager(string tableName)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        public PiOrganizeManager(IDbProvider dbProvider)
            : this()
        {
            DBProvider = dbProvider;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        public PiOrganizeManager(UserInfo userInfo)
            : this()
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        /// <param name="userInfo">用户信息</param>
        public PiOrganizeManager(IDbProvider dbProvider, UserInfo userInfo)
            : this(dbProvider)
        {
            UserInfo = userInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbProvider">数据库连接</param>
        /// <param name="userInfo">用户信息</param>
        /// <param name="tableName">指定表名</param>
        public PiOrganizeManager(IDbProvider dbProvider, UserInfo userInfo, string tableName)
            : this(dbProvider, userInfo)
        {
            base.CurrentTableName = tableName;
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id">主键</param>
        public PiOrganizeEntity GetEntity(string id)
        {
            return GetEntity(int.Parse(id));
        }

        public PiOrganizeEntity GetEntity(int id)
        {
            PiOrganizeEntity piOrganizeEntity = new PiOrganizeEntity(this.GetDT(PiOrganizeTable.FieldId, id));
            return piOrganizeEntity;
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="piOrganizeEntity">实体</param>
        public int AddEntity(PiOrganizeEntity piOrganizeEntity, out string statusCode)
        {
            int returnValue = 0;
            string sequence = string.Empty;
            statusCode = string.Empty;
            string[] names = new string[] { PiOrganizeTable.FieldParentId,PiOrganizeTable.FieldFullName,PiOrganizeTable.FieldDeleteMark};
            object[] values = new object[] { piOrganizeEntity.ParentId,piOrganizeEntity.FullName,piOrganizeEntity.DeleteMark};
            if (this.Exists(names, values))
            {
                // 名称已重复
                statusCode = StatusCode.ErrorNameExist.ToString();
            }
            else
            {
                if (piOrganizeEntity.SortCode == null || piOrganizeEntity.SortCode == 0)
                {
                    CiSequenceManager sequenceManager = new CiSequenceManager(DBProvider, this.Identity);
                    sequence = sequenceManager.GetSequence(this.CurrentTableName);
                    piOrganizeEntity.SortCode = int.Parse(sequence);
                }

                SQLBuilder sqlBuilder = new SQLBuilder(DBProvider, this.Identity, this.ReturnId);
                sqlBuilder.BeginInsert(this.CurrentTableName, PiOrganizeTable.FieldId);
                if (!this.Identity)
                {
                    sqlBuilder.SetValue(PiOrganizeTable.FieldId, piOrganizeEntity.Id);
                }
                else
                {
                    if (!this.ReturnId && (DBProvider.CurrentDbType == CurrentDbType.Oracle || DBProvider.CurrentDbType == CurrentDbType.DB2))
                    {
                        if (DBProvider.CurrentDbType == CurrentDbType.Oracle)
                        {
                            sqlBuilder.SetFormula(PiOrganizeTable.FieldId, "SEQ_" + this.CurrentTableName.ToUpper() + ".NEXTVAL ");
                        }
                        if (DBProvider.CurrentDbType == CurrentDbType.DB2)
                        {
                            sqlBuilder.SetFormula(PiOrganizeTable.FieldId, "NEXT VALUE FOR SEQ_" + this.CurrentTableName.ToUpper());
                        }
                    }
                    else
                    {
                        if (this.Identity && (DBProvider.CurrentDbType == CurrentDbType.Oracle || DBProvider.CurrentDbType == CurrentDbType.DB2))
                        {
                            //if (piOrganizeEntity.Id == null)
                            //{
                            //    if (string.IsNullOrEmpty(sequence))
                            //    {
                            //        //CiSequenceManager sequenceManager = new CiSequenceManager(DBProvider, this.Identity);
                            //        //sequence = sequenceManager.GetSequence(this.CurrentTableName);
                            //    }
                            //    piOrganizeEntity.Id = int.Parse(sequence);
                            //}
                            //sqlBuilder.SetValue(PiOrganizeTable.FieldId, piOrganizeEntity.Id);
                        }
                    }
                }
                this.SetEntity(sqlBuilder, piOrganizeEntity);
                //if (UserInfo != null)
                //{
                //    sqlBuilder.SetValue(PiOrganizeTable.FieldCreateUserId, UserInfo.Id);
                //    sqlBuilder.SetValue(PiOrganizeTable.FieldCreateBy, UserInfo.RealName);
                //}
                sqlBuilder.SetDBNow(PiOrganizeTable.FieldCreateOn);
                sqlBuilder.SetDBNow(PiOrganizeTable.FieldModifiedOn);
                if (this.Identity && (DBProvider.CurrentDbType == CurrentDbType.SqlServer || DBProvider.CurrentDbType == CurrentDbType.Access))
                {
                    returnValue = sqlBuilder.EndInsert();
                    // 运行成功
                    statusCode = StatusCode.OKAdd.ToString();
                }
                else
                {
                    sqlBuilder.EndInsert();
                }
            }
            return returnValue;
        }

        public int Update(PiOrganizeEntity organizeEntity, out string statusCode)
        {
            int returnValue = 0;
            string[] names = new string[] { PiOrganizeTable.FieldParentId, PiOrganizeTable.FieldFullName, PiOrganizeTable.FieldDeleteMark };
            Object[] values = new object[] { organizeEntity.ParentId, organizeEntity.FullName, 0 };

            if (this.Exists(names, values, organizeEntity.Id))
            {
                // 名称已重复
                statusCode = StatusCode.ErrorNameExist.ToString();
            }
            else
            {
                // 检查编号是否重复
                names = new string[] { PiOrganizeTable.FieldCode, PiOrganizeTable.FieldDeleteMark };
                values = new object[] { organizeEntity.Code, 0 };

                if (organizeEntity.Code.Length > 0 && this.Exists(names, values, organizeEntity.Id))
                {
                    // 编号已重复
                    statusCode = StatusCode.ErrorCodeExist.ToString();
                }
                else
                {
                    returnValue = this.UpdateEntity(organizeEntity);
                    if (returnValue == 1)
                    {
                        statusCode = StatusCode.OKUpdate.ToString();
                    }
                    else
                    {
                        statusCode = StatusCode.ErrorChanged.ToString();
                    }
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="piOrganizeEntity">实体</param>
        public int UpdateEntity(PiOrganizeEntity piOrganizeEntity)
        {
            SQLBuilder sqlBuilder = new SQLBuilder(DBProvider);
            sqlBuilder.BeginUpdate(this.CurrentTableName);
            this.SetEntity(sqlBuilder, piOrganizeEntity);
            sqlBuilder.SetDBNow(PiOrganizeTable.FieldModifiedOn);
            sqlBuilder.SetWhere(PiOrganizeTable.FieldId, piOrganizeEntity.Id);
            return sqlBuilder.EndUpdate();
        }

        /// <summary>
        /// 设置实体
        /// </summary>
        /// <param name="piOrganizeEntity">实体</param>
        private void SetEntity(SQLBuilder sqlBuilder, PiOrganizeEntity piOrganizeEntity)
        {
            sqlBuilder.SetValue(PiOrganizeTable.FieldParentId, piOrganizeEntity.ParentId);
            sqlBuilder.SetValue(PiOrganizeTable.FieldCode, piOrganizeEntity.Code);
            sqlBuilder.SetValue(PiOrganizeTable.FieldShortName, piOrganizeEntity.ShortName);
            sqlBuilder.SetValue(PiOrganizeTable.FieldFullName, piOrganizeEntity.FullName);
            sqlBuilder.SetValue(PiOrganizeTable.FieldCategory, piOrganizeEntity.Category);
            sqlBuilder.SetValue(PiOrganizeTable.FieldOuterPhone, piOrganizeEntity.OuterPhone);
            sqlBuilder.SetValue(PiOrganizeTable.FieldInnerPhone, piOrganizeEntity.InnerPhone);
            sqlBuilder.SetValue(PiOrganizeTable.FieldFax, piOrganizeEntity.Fax);
            sqlBuilder.SetValue(PiOrganizeTable.FieldPostalcode, piOrganizeEntity.Postalcode);
            sqlBuilder.SetValue(PiOrganizeTable.FieldAddress, piOrganizeEntity.Address);
            sqlBuilder.SetValue(PiOrganizeTable.FieldWeb, piOrganizeEntity.Web);
            sqlBuilder.SetValue(PiOrganizeTable.FieldManager, piOrganizeEntity.Manager);
            sqlBuilder.SetValue(PiOrganizeTable.FieldLayer, piOrganizeEntity.Layer);
            sqlBuilder.SetValue(PiOrganizeTable.FieldAssistantManager, piOrganizeEntity.AssistantManager);
            sqlBuilder.SetValue(PiOrganizeTable.FieldIsInnerOrganize, piOrganizeEntity.IsInnerOrganize);
            sqlBuilder.SetValue(PiOrganizeTable.FieldEnabled, piOrganizeEntity.Enabled);
            sqlBuilder.SetValue(PiOrganizeTable.FieldBank, piOrganizeEntity.Bank);
            sqlBuilder.SetValue(PiOrganizeTable.FieldBankAccount, piOrganizeEntity.BankAccount);
            sqlBuilder.SetValue(PiOrganizeTable.FieldSortCode, piOrganizeEntity.SortCode);
            sqlBuilder.SetValue(PiOrganizeTable.FieldDescription, piOrganizeEntity.Description);
            sqlBuilder.SetValue(PiOrganizeTable.FieldModifyUserId, piOrganizeEntity.ModifyUserId);
            sqlBuilder.SetValue(PiOrganizeTable.FieldModifiedBy, piOrganizeEntity.ModifiedBy);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>影响行数</returns>
        public int Delete(int id)
        {
            return this.Delete(PiOrganizeTable.FieldId, id);
        }

        public int AddEntity(PiOrganizeEntity entity)
        { 
            string statusCode = string.Empty;
            return this.AddEntity(entity, out statusCode);
        }

        public override int BatchSave(DataTable dataTable)
        {
            int returnValue = 0;
            PiOrganizeEntity organizeEntity = new PiOrganizeEntity();
            foreach (DataRow dataRow in dataTable.Rows)
            {
                // 删除状态
                if (dataRow.RowState == DataRowState.Deleted)
                {
                    string id = dataRow[PiOrganizeTable.FieldId, DataRowVersion.Original].ToString();
                    if (id.Length > 0)
                    {
                        returnValue += this.DeleteEntity(id);
                    }
                }
                // 被修改过
                if (dataRow.RowState == DataRowState.Modified)
                {
                    string id = dataRow[PiOrganizeTable.FieldId, DataRowVersion.Original].ToString();
                    if (id.Length > 0)
                    {
                        organizeEntity.GetFrom(dataRow);
                        returnValue += this.UpdateEntity(organizeEntity);
                    }
                }
                // 添加状态
                if (dataRow.RowState == DataRowState.Added)
                {
                    organizeEntity.GetFrom(dataRow);
                    returnValue += this.AddEntity(organizeEntity)> 0 ? 1 : 0;
                }
                if (dataRow.RowState == DataRowState.Unchanged)
                {
                    continue;
                }
                if (dataRow.RowState == DataRowState.Detached)
                {
                    continue;
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="parentId">父级主键</param>
        /// <returns>影响行数</returns>
        public int MoveTo(string id, string parentId)
        {
            return this.SetProperty(id, PiOrganizeTable.FieldParentId, parentId);
        }

        public DataTable GetInnerOrganize(string organizeId)
        {
            List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldIsInnerOrganize, 1));
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldDeleteMark, 0));
            return this.GetDT(parameters, PiOrganizeTable.FieldSortCode);
        }

        public DataTable GetCompanyDT(string organizeId)
        {
            return this.GetDT(new KeyValuePair<string, object>(PiOrganizeTable.FieldCategory, "Company"), PiOrganizeTable.FieldSortCode);
        }

        public DataTable GetCompanyDTByName(string organizeName)
        {
            List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldCategory, "Company"));
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldFullName, organizeName));
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldDeleteMark, 0));
            return this.GetDT(parameters, PiOrganizeTable.FieldSortCode);
        }

        public DataTable GetDepartmentDT(string organizeId = null)
        {
            if (String.IsNullOrEmpty(organizeId))
            {
                List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
                parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldCategory, "Department"));
                parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldEnabled, 1));
                parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldDeleteMark, 0));
                return this.GetDT(parameters, PiOrganizeTable.FieldSortCode);
            }
            return this.GetDT(new KeyValuePair<string, object>(PiOrganizeTable.FieldParentId, organizeId), new KeyValuePair<string, object>(PiOrganizeTable.FieldCategory, "Department"), PiOrganizeTable.FieldSortCode);
        }

        public DataTable GetFullNameDepartment(DataTable dataTable)
        {
            foreach (DataRow dr in dataTable.Rows)
            {
                PiOrganizeEntity subCompanyNameEntity = RDIFrameworkService.Instance.OrganizeService.GetEntity(UserInfo, dr[PiOrganizeTable.FieldParentId].ToString());
                dr[PiOrganizeTable.FieldFullName] = subCompanyNameEntity.FullName.ToString() + "--" + dr[PiOrganizeTable.FieldFullName].ToString();
                PiOrganizeEntity companyEntity = RDIFrameworkService.Instance.OrganizeService.GetEntity(UserInfo, subCompanyNameEntity.ParentId.ToString());
                dr[PiOrganizeTable.FieldFullName] = companyEntity.FullName.ToString() + "--" + dr[PiOrganizeTable.FieldFullName].ToString();
            }
            return dataTable;
        }

        public DataTable GetDepartmentDTByName(string organizeName)
        {
            List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldCategory, "Department"));
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldFullName, organizeName));
            parameters.Add(new KeyValuePair<string, object>(PiOrganizeTable.FieldDeleteMark, 0));
            return this.GetDT(parameters, PiOrganizeTable.FieldSortCode);
        }
    }
}
